package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private FollowMapper followMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 当前用户关注/取关该用户
     *
     * @param id
     * @param isFollow
     * @return
     */
    public Result followOrNot(Long id, Boolean isFollow) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.当前用户要关注该用户
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(id);
        String key = FOLLOW_KEY + userId;
        if (isFollow) {
            //插入follow
            boolean success = save(follow);
            if (success) {
                //将关注信息加入redis的set集合
                stringRedisTemplate.opsForSet().add(key, id.toString());
            }
        } else {
            //3.当前用户要取关,
            followMapper.deleteFollow(follow);
            //将关注信息加入redis的set集合
            stringRedisTemplate.opsForSet().remove(key, id.toString());
        }
        return Result.ok();
    }

    /**
     * 查看当前用户是否关注该用户
     *
     * @param followId
     * @return
     */
    public Result queryFollowOrNot(Long followId) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询当前用户是否关注该用户
        Integer count = query()
                .eq("user_id", userId)
                .eq("follow_user_id", followId)
                .count();
        return Result.ok(count > 0);
    }

    /**
     * 查询共同关注
     * @param id
     * @return
     */
    public Result queryCommonFollow(Long id) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String keyCurrent = FOLLOW_KEY + userId;
        String keyOther =  FOLLOW_KEY + id;
        //2.查询redis中的交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(keyCurrent, keyOther);

        //3.交集是否为空
        if(intersect == null || intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //4.处理交集,全都转为List<Long>类型
        List<Long> idList = intersect
                .stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        //5.查询数据库，将查到的List<User>转为List<UserDTO>
        List<UserDTO> userDTOS = userService.listByIds(idList)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
